/*action create by pionner code builder*/
package com.pioneer.app.dev.osuser.user;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.Transaction;

import com.app.Const;
import com.app.util.MD5;
import com.gotop.sms.fysms.Bacterin;
import com.gotop.sms.fysms.BacterinDAO;
import com.gotop.sms.fysms.BacterinService;
import com.gotop.sms.fysms.UserBacterin;
import com.gotop.sms.fysms.UserBacterinDAO;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;


public class UserlistAction implements Action, ServletRequestAware,ServletResponseAware,Serializable {

	// key
	private java.lang.Integer id;
	private String code;
	private java.lang.Integer[] ids;
	private Userlist userlist;
	private java.lang.String userName;
	private java.lang.String userPwd;
	private java.lang.String telphone;
	private java.lang.String smsStr;
	private java.lang.Integer departmentId;
	private java.lang.String address;
	private java.lang.String agender;
	private String rtPage=null;
	private List objects=null;
	private String condition=null;
	private String fromTree=null;
	private String message=null;
	private String oldpwd=null;
	private String cname=null;
	private Date birthday;
	private File userfile;
	private File userFileTxt;
	private String userId;
	private String carNo;
	private String kind;
	private Integer smsState;
	
	public Integer getSmsState() {
		return smsState;
	}
	public void setSmsState(Integer smsState) {
		this.smsState = smsState;
	}
	public String getKind() {
		return kind;
	}
	public void setKind(String kind) {
		this.kind = kind;
	}
	private HttpServletResponse response;
	private HttpServletRequest request;
	
	public String getCarNo() {
		return carNo;
	}
	public void setCarNo(String carNo) {
		this.carNo = carNo;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getOldpwd() {
		return oldpwd;
	}
	public void setOldpwd(String oldpwd) {
		this.oldpwd = oldpwd;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	public UserlistAction(){
	}
	/** full constructor */
	public UserlistAction(java.lang.String userName,java.lang.String userPwd,java.lang.String telphone,java.lang.String smsStr,java.lang.Integer departmentId,java.lang.String addres){
		this.userName=userName;
		this.userPwd=userPwd;
		this.telphone=telphone;
		this.smsStr=smsStr;
		this.departmentId=departmentId;
		this.address=address;

	}
	public void setId(java.lang.Integer id){
		this.id=id;
	}
	public java.lang.Integer getId(){
		return id;
	}

	public void setIds(java.lang.Integer[] ids){
		this.ids=ids;
	}
	public java.lang.Integer[] getIds(){
		return ids;
	}

	public void setUserlist(Userlist userlist){
		this.userlist=userlist;
	}
	public Userlist getUserlist(){
		return userlist;
	}

	public void setUserName(java.lang.String userName){
		this.userName=userName;
	}
	public java.lang.String getUserName(){
		return userName;
	}

	public void setUserPwd(java.lang.String userPwd){
		this.userPwd=userPwd;
	}
	public java.lang.String getUserPwd(){
		return userPwd;
	}

	public void setTelphone(java.lang.String telphone){
		this.telphone=telphone;
	}
	public java.lang.String getTelphone(){
		return telphone;
	}

	public void setSmsStr(java.lang.String smsStr){
		this.smsStr=smsStr;
	}
	public java.lang.String getSmsStr(){
		return smsStr;
	}

	public void setDepartmentId(java.lang.Integer departmentId){
		this.departmentId=departmentId;
	}
	public java.lang.Integer getDepartmentId(){
		return departmentId;
	}

	public void setAddress(java.lang.String address){
		this.address=address;
	}
	public java.lang.String getAddress(){
		return address;
	}

	public List getObjects() {
		return objects;
	}

	public void setObjects(List objects) {
		this.objects = objects;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public String execute() throws Exception {
		return "SUCESS";
	}

	public String doList(){
		if(null==this.rtPage){
			this.rtPage="list";			
		}else{
			if(null!=this.departmentId && null!=this.cname)
				condition="departmentId="+departmentId+ " and cname like '%"+cname+"%'";
			else if(null!=this.departmentId)
				condition="departmentId="+departmentId;
			else if(null!=this.cname)
				condition="cname like '%"+cname+"%'";
		}
		
		UserlistDAO dao=new UserlistDAO();
		this.objects=dao.findByCondition(condition);
		dao.getSession().close();
		if("fyList".equalsIgnoreCase(rtPage)){
			
			if(null!=this.objects){
				Userlist user=null;
				BacterinService bs=new BacterinService();
				BacterinDAO bdao=new BacterinDAO();
				Iterator it=	this.objects.iterator();
				while(it.hasNext()){
					user=(Userlist)it.next();
					UserBacterin ub=bs.getLastBacterin(user.getId());
					if(ub!=null){
					Integer bid=ub.getBacterinId();
					Bacterin bvo=null;
					bvo=bdao.findById(bid);
					user.setBacterin(bvo.getName());
					user.setInjectDate(ub.getOrderTimeS());
					}
				}
			}
		}
		return this.rtPage;
	}
	
	public String doBatchAdd(){
		int count=0;
		int right=0;
		int fileType=0;
		if(null!=this.userfile && userfile.exists()){
		fileType=1;
			try {
				FileInputStream is=new FileInputStream(this.userfile);
				WorkbookSettings workbookSettings = new WorkbookSettings();
				workbookSettings.setEncoding("UTF-8");
				Workbook rwb = Workbook.getWorkbook(is, workbookSettings);
				Sheet st = rwb.getSheet(0);
      
  			int rownum = st.getRows();
  			UserlistDAO dao=new UserlistDAO();
  			count=rownum-2;
  			for (int i = 2; i < rownum; i++) {
  				boolean flag=true;
  				this.userPwd="888888";
  				this.telphone=null;
  				this.userId=null;
  				this.address=null;
  				this.carNo=null;
  				this.birthday=null;
  				this.cname=null;
  				Cell[] cells = st.getRow(i);
  				
  				
  				for(int j=0;j<cells.length;j++){
  					if(j==0){
  						this.userName=cells[0].getContents();
  						condition="userName='"+userName+"'";
  						List list=dao.findByCondition(condition);
  						if(list.size()>0||this.userName.equals("")){
  							flag=false;
  							break;
  						}  						
  					}else if(j==1){
  						this.cname=cells[1].getContents();
  						if(this.cname.equals("")){
  							flag=false;
  							break;
  						}
  					}else if(j==2){
  						this.telphone=cells[2].getContents();
  						if(this.telphone.equals("")){
  							flag=false;
  							break;
  						}
  					}else if(j==3){
  						SimpleDateFormat   formatter   =   new   SimpleDateFormat("yyyy-MM-dd");  				
  		  				this.birthday=formatter.parse(cells[3].getContents());
  		  				if(cells[3].getContents().equals("")){
  		  					flag=false;
  		  					break;
  		  				}
  					}else if(j==4){
  						if(!(cells[4].getContents()).equals(""))
  						this.userPwd=cells[4].getContents();
  					}else if(j==5){
  						this.userId=cells[5].getContents();
  					}else if(j==6){
  						this.address=cells[6].getContents();
  					}else if(j==7){
  						this.carNo=cells[7].getContents();  						
  					}else if(j==8){
  						this.kind=cells[8].getContents();
  					}
  				} 				
  				if(flag&&cname!=null&&telphone!=null&&birthday!=null){
  					right++;
  					doSave();
  					
  					BacterinService bs=new BacterinService();
					bs.userBacterinInit(id);
					id=null;
  				}
  			}
  			
			}catch (Exception e) {
				
				e.printStackTrace();
			}
		}
	if(null!=this.userFileTxt && userFileTxt.exists()){
		fileType=2;
		try {
			UserlistDAO dao=new UserlistDAO();
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(this.userFileTxt)));
			String data = null;
			while((data = br.readLine())!=null)
			{
				count++;
				data=data.trim();
				if(data.length()==11){
					this.userName=data;
					this.userPwd="888888";
					this.telphone=data;
					right++;
					doSave();
					
				}				
			}			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
		int wrong=count-right;
		this.message="共解析"+count+"条，成功"+right+"条，失败"+wrong+"条";
		if(wrong>0){
			if(fileType==1)
				this.message+="，请检查账号是否重复,必填项是否填写！";
			if(fileType==2)
				this.message+="，请检查手机号码是否正确！";
		}			
		else
			this.message+=",导入成功!";
		return "list";
	}

	public String doAdd(){
		return "add";
	}
	
	public String doExport(){
		condition="departmentId="+departmentId;
		UserlistDAO dao=new UserlistDAO();
		this.objects=dao.findByCondition(condition);
		dao.getSession().close();			
			if(null!=this.objects){
				Userlist user=null;
				BacterinService bs=new BacterinService();
				BacterinDAO bdao=new BacterinDAO();
				Iterator it=	this.objects.iterator();
				while(it.hasNext()){
					user=(Userlist)it.next();
					UserBacterin ub=bs.getLastBacterin(user.getId());
					if(ub!=null){
					Integer bid=ub.getBacterinId();
					Bacterin bvo=null;
					bvo=bdao.findById(bid);
					user.setBacterin(bvo.getName());
					user.setInjectDate(ub.getOrderTimeS());
					}
				}
			}
		
		try {

			response.setContentType("application/vnd.ms-excel");
			response.addHeader("Content-Disposition",
					"attachment;filename=PeopleInfo.xls");
			OutputStream os = response.getOutputStream();

			WritableWorkbook workbook = Workbook.createWorkbook(os);// 创建工作薄

			WritableSheet worksheet = workbook.createSheet("record", 0);// 创建第一个工作表，name:工作表名称

			Label label = null;// 用于写入文本内容到工作表中去

			// 开始写入第一行，即标题栏
			String[] title = { "编号", "姓名", "性别", "生日", "手机号",
					"要注射疫苗", "注射时间","地址","性质"};
			for (int i = 0; i < title.length; i++) {

				label = new Label(i, 0, title[i]);// 参数依次代表列数、行数、内容

				worksheet.addCell(label);// 写入单元格

			}

			// 开始写入内容
			for (int i = 0; i < objects.size(); i++) {

				Userlist ul=(Userlist)objects.get(i);//获取一条记录
				SimpleDateFormat   formatter   =   new   SimpleDateFormat("yyyy-MM-dd");  	
				label = new Label(0, i + 1, ul.getCode());
				worksheet.addCell(label);
				label = new Label(1, i + 1, ul.getCname());
				worksheet.addCell(label);
				label = new Label(2, i + 1, ul.getAgender());
				worksheet.addCell(label);
				label = new Label(3, i + 1, formatter.format(ul.getBirthday()));
				worksheet.addCell(label);
				label = new Label(4, i + 1, ul.getTelphone());							
				worksheet.addCell(label);
				label = new Label(5, i + 1, ul.getBacterin());
				worksheet.addCell(label);
				label = new Label(6, i + 1, ul.getInjectDate());
				worksheet.addCell(label);
				label = new Label(7, i + 1, ul.getAddress());					
				worksheet.addCell(label);				
				label = new Label(8, i + 1, ul.getKind());					
				worksheet.addCell(label);				
			}
			workbook.write();
			workbook.close();			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return "list";
	}

	public String doEdit(){
		UserlistDAO dao=new UserlistDAO();
		this.userlist=dao.findById(id);
		this.sedObj();;
		dao.getSession().close();
		return "edit";
	}

	public String doSave(){
		Transaction tx=null;
		try {
			UserlistDAO dao=new UserlistDAO();
			String OldPass=null;
			if(id!=null){
				this.userlist=dao.findById(id);
				OldPass=this.userlist.getUserPwd();
			}			
			this.buildObj();
			if(this.userPwd.equals("")||this.userPwd==null){
				this.userlist.setUserPwd(OldPass);
			}else{
				this.userlist.setUserPwd(MD5.ToMD5(this.userlist.getUserPwd()));
			}
			if(this.kind!=null){
			if(this.kind.equals("固定")){
				this.userlist.setSmsState(1);
			}else{
				this.userlist.setSmsState(0);
			}
			}
			tx=dao.getSession().beginTransaction();
			if(null==this.userlist.getId()){
//			insert a new object
			//gave the object id by database 
				
				dao.add(userlist);
				this.id=this.userlist.getId();
				this.request.setAttribute("userId", this.id);
			}else{
//			update the object
				dao.getSession().clear();				
				UserBacterinDAO ubDao=new UserBacterinDAO();
				String condition="userId='"+id+"'";
				List list=ubDao.findByCondition(condition);
				for(int i=0;i<list.size();i++){
					UserBacterin ub=(UserBacterin)list.get(i);
					if(smsState!=null){
					if(this.smsState.equals(1)){
						ub.setState(1);
					}else{
						ub.setState(0);
					}
					}
					else{
						if(this.kind!=null){
							if(this.kind.equals("固定")){
								ub.setState(1);
							}else{
								ub.setState(0);
							}
						}
					}
					ubDao.update(ub);
				}
				userlist.setSmsState(smsState);
				dao.update(userlist);
			}
			tx.commit();
			dao.getSession().close();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return "error";
		}
		if(null!=fromTree){
			rtPage= "detail";
		}
		if(null==rtPage)
			rtPage= "list";
		return rtPage;
	}
	public String getMaxCode(){
		String prex=this.request.getParameter("prex");
		UserlistDAO uld=new UserlistDAO();
		String code=uld.findMaxCode(prex);
		try {
			if(null==code){
				code="0";
			}
			this.response.getOutputStream().write(code.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String doDetail(){
			UserlistDAO dao=new UserlistDAO();
		this.userlist=dao.findById(id);
		this.sedObj();;
		dao.getSession().close();
		return "detail";
	}
	public String doSelf(){
		Userlist user=null;
		this.userlist=(Userlist)ActionContext.getContext().getSession().get(Const.SESSION_USER_OBJECT);
		//UserlistDAO dao=new UserlistDAO();
		//this.userlist=dao.findById();
		this.sedObj();;
		//dao.getSession().close();
		return "detail";
	}
	public String doDelete(){
		try{
			UserlistDAO dao=new UserlistDAO();
			dao.deleteObjs(ids);
			dao.getSession().close();
			return "list";
		}catch(Exception e){
			return "error";
		}
	}
	public String doSMS(){
		UserlistDAO dao=new UserlistDAO();
		for(int i=0;i<ids.length;i++){
			Userlist ul=dao.findById(ids[i]);
			ul.setSmsState(1);
			dao.update(ul);
		}
		
		
		
		rtPage="fyList";
		//departmentId=15;
		
		if(null==this.rtPage){
			this.rtPage="list";			
		}else{
			if(null!=this.departmentId && null!=this.cname)
				condition="departmentId="+departmentId+ " and cname like '%"+cname+"%'";
			else if(null!=this.departmentId)
				condition="departmentId="+departmentId;
			else if(null!=this.cname)
				condition="cname like '%"+cname+"%'";
		}
		
		
		this.objects=dao.findByCondition(condition);
		dao.getSession().close();
		if("fyList".equalsIgnoreCase(rtPage)){
			
			if(null!=this.objects){
				Userlist user=null;
				BacterinService bs=new BacterinService();
				BacterinDAO bdao=new BacterinDAO();
				Iterator it=	this.objects.iterator();
				while(it.hasNext()){
					user=(Userlist)it.next();
					UserBacterin ub=bs.getLastBacterin(user.getId());
					if(ub!=null){
					Integer bid=ub.getBacterinId();
					Bacterin bvo=null;
					bvo=bdao.findById(bid);
					user.setBacterin(bvo.getName());
					user.setInjectDate(ub.getOrderTimeS());
					}
				}
			}
		}
		return this.rtPage;
		
	}

	private void buildObj(){
		this.userlist=new Userlist();
		this.userlist.setId(this.id);
		this.userlist.setCode(this.code);
		this.userlist.setUserName(this.userName);
		this.userlist.setUserPwd(this.userPwd);	
		this.userlist.setTelphone(this.telphone);
		this.userlist.setSmsStr(this.smsStr);
		this.userlist.setDepartmentId(this.departmentId);
		this.userlist.setAddress(this.address);
		this.userlist.setCname(this.cname);
		this.userlist.setBirthday(this.birthday);
		this.userlist.setUserId(this.userId);
		this.userlist.setCarNo(this.carNo);
		this.userlist.setAgender(this.agender);
		this.userlist.setKind(this.kind);
		this.userlist.setUserId(userId);
		this.userlist.setSmsState(smsState);
	}
	private void sedObj(){

		if(null!=this.userlist){
			this.id=this.userlist.getId();
			this.code=this.userlist.getCode();
			this.userName=this.userlist.getUserName();
			this.userPwd=this.userlist.getUserPwd();
			this.telphone=this.userlist.getTelphone();
			this.smsStr=this.userlist.getSmsStr();
			this.departmentId=this.userlist.getDepartmentId();
			this.address=this.userlist.getAddress();
			this.cname=this.userlist.getCname();			
			this.birthday=this.userlist.getBirthday();
			this.agender=this.userlist.getAgender();
			this.kind=this.userlist.getKind();
			this.userId=this.userlist.getUserId();
			this.smsState=this.userlist.getSmsState();
		}
	}
	public String doPasswordEdit(){
		String rtPage="password";
		Userlist user = (Userlist)ActionContext.getContext().getSession().get(Const.SESSION_USER_OBJECT);
		if(null==user){
			this.message="你已经推出系统，请重新登陆！";
			return rtPage;
		}
		UserlistDAO dao=new UserlistDAO();
		user=dao.findById(user.getId());
		if(!user.getUserPwd().equalsIgnoreCase(MD5.ToMD5(this.oldpwd))){
			this.message="你输入的旧密码不正确！";
			return rtPage;
		}
		this.userPwd=MD5.ToMD5(this.userPwd);
		user.setUserPwd(this.userPwd);
		if(AdminService.USER_NAME.equalsIgnoreCase(user.getUserName())){
			AdminService.getInst().editPassword(this.userPwd);
		}else{
		 Transaction tx=	dao.getSession().beginTransaction();
		 
			dao.update(user);
			tx.commit();
		}
		this.message="密码修改成功，请牢记你的新密码！";
		return rtPage;
	}
	public String getFromTree() {
		return fromTree;
	}
	public void setFromTree(String fromTree) {
		this.fromTree = fromTree;
	}
	public String getRtPage() {
		return rtPage;
	}
	public void setRtPage(String rtPage) {
		this.rtPage = rtPage;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public File getUserfile() {
		return userfile;
	}
	public void setUserfile(File userfile) {
		this.userfile = userfile;
	}

	public void setServletRequest(HttpServletRequest arg0) {
		this.request=arg0;
		
	}
	public void setServletResponse(HttpServletResponse arg0) {
		this.response=arg0;
		
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public File getUserFileTxt() {
		return userFileTxt;
	}
	public void setUserFileTxt(File userFileTxt) {
		this.userFileTxt = userFileTxt;
	}
	public java.lang.String getAgender() {
		return agender;
	}
	public void setAgender(java.lang.String agender) {
		this.agender = agender;
	}

	
}